package com.chen.service.impl;

import com.chen.dao.BaseDAO;
import com.chen.pojo.Customer;
import com.chen.pojo.PageBean;
import com.chen.service.CustomerService;
import com.chen.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * com.chen.service.impl
 * 作者      : 陈晓
 * 描述      :
 * 创建日期  : 2018/4/29
 * 修改日期  :
 */
@Service("/customerService")
@Transactional
public class CustomerServiceImpl implements CustomerService {

  @Autowired
  private BaseDAO<Customer> baseDAO;

  private static List<Object> list;

  public void insert(Customer customer)throws Exception {
    baseDAO.save(customer);
  }

  public List<Customer> getList(Customer customer, PageBean pageBean)throws Exception {
    StringBuilder sb = new StringBuilder("select c from Customer as c ");
    list = new ArrayList<Object>();
    String sql = getSql(customer, sb);
    String hql = sql + " order by c.id desc ";
    return baseDAO.find(hql.replaceFirst("and", "where"), list, pageBean);
  }

  public long getCount(Customer customer)throws Exception {
    StringBuilder sb = new StringBuilder("select count(c) from Customer as c ");
    list = new ArrayList<Object>();
    String sql = getSql(customer, sb);
    if (list.size() > 0)
      return baseDAO.count(sql.replaceFirst("and", "where"),list);
    return baseDAO.count(sql.replaceFirst("and", "where"));
  }

  /**
   * 获得执行语句Sql
   *
   * @param customer 对象
   * @param sb       sql语句
   * @return 返回sql语句
   */
  private String getSql(Customer customer, StringBuilder sb) {
    if (customer != null) {
      if (StringUtil.isNotEmpty(customer.getUsername())) {
        sb.append(" and c.username like ? ");
        list.add("%"+customer.getUsername()+"%");
      }
      if (StringUtil.isNotEmpty(customer.getCompany())) {
        sb.append(" and c.company like ? ");
        list.add("%"+customer.getCompany()+"%");
      }
      if (StringUtil.isNotEmpty(customer.getAddress())) {
        sb.append(" and c.address like ? ");
        list.add("%"+customer.getAddress()+"%");
      }
      if (StringUtil.isNotEmpty(customer.getPhone())) {
        sb.append(" and c.phone like ? ");
        list.add("%"+customer.getPhone()+"%");
      }
    }
    return sb.toString();
  }

  /**
   * 获得参数值
   *
   * @param list 参数值列表
   * @return 参数值
   */
  private Object[] getParams(List<String> list) {
    Object[] params = new Object[list.size()];
    for (int i = 0; i < list.size(); i++) {
      params[i] = list.get(i);
    }
    return params;
  }
}
